package init.luoyu.easymonitor.base.handler;

import init.luoyu.easymonitor.base.model.ServiceResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>全局异常捕获配置类型</p>
 * @author LuoYu
 * 2021/4/4
 **/
@Slf4j
@ControllerAdvice
public class ControllerExceptionHandler {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ServiceResult<String> validExceptionHandler(Exception e){

        if(e instanceof  MethodArgumentNotValidException) {
            MethodArgumentNotValidException validException = (MethodArgumentNotValidException) e;
            List<ObjectError> errors = validException.getAllErrors();
            List<String> errorMessages = errors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
            log.error("参数校验失败 ----> Error:{}",errorMessages);
            return ServiceResult.error(errorMessages.toString());
        }
        log.error("发生错误 ----> Error:{}",e.getMessage());
        return ServiceResult.error(e.getMessage());
    }



}
